package com.kongjs.online.preview.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class HttpUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    public static void download(String url,File file){
        RestTemplate restTemplate = new RestTemplate();
        RequestCallback requestCallback = new RequestCallback() {
            @Override
            public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
                clientHttpRequest.getHeaders().clear();
            }
        };
        ResponseExtractor<File> responseExtractor = clientHttpResponse -> {
            HttpHeaders headers = clientHttpResponse.getHeaders();
            long contentLength = headers.getContentLength();
            if (clientHttpResponse.getStatusCode().is2xxSuccessful()) {
                InputStream inputStream = clientHttpResponse.getBody();
                FileCopyUtils.copy(inputStream, new FileOutputStream(file));
                if (contentLength == file.length()) {
                    System.out.println("下载完成...");
                }else {
                    throw new IOException("下载失败");
                }
            }
            return file;
        };
        restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
    }
}